import { userService } from '@/services/test-services';
import type { userAPI } from '@/models/models';
import type { Effect, Reducer, Subscription } from '@umijs/max';
import { Random } from 'mockjs';

const { queryUserDataList } = userService;

export interface IndexModelType {
  namespace: 'userModel';
  state: userAPI.IState;
  effects: {
    queryUserDataList: Effect;
  };
  reducers: {
    save: Reducer<userAPI.IState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'userModel',

  state: {
    userList: [],
  },

  effects: {
    *queryUserDataList({}, { call, put }): any {
      const response = yield call(queryUserDataList, {});
      console.log('userList', response);
      try {
        if (response.success) {
          const userList = response.data.list.map(
            (user: Pick<userAPI.userDataItem, 'id' | 'name' | 'email'>, index: number) => {
              return {
                ...user,
                address: Random.county(true),
                avatar: `https://picsum.photos/200/200?random=${index}`,
              };
            },
          );
          yield put({
            type: 'save',
            payload: {
              userList,
            },
          });
        }
      } catch (error) {
        console.error(error);
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen((listener) => {
        const { location } = listener;
        if (location.pathname.includes('/X6Cases')) {
          dispatch({
            type: 'queryUserDataList',
          });
        }
      });
    },
  },
};

export default IndexModel;
